package com.cx.util.jdbc;

import java.sql.*;

/**
 * @author zhangshuai
 * @version V1.0
 * @Project Java2_26
 * @Package com.cx.util.jdbc
 * @Description:
 * @Date 2025/6/5 9:28
 */

public class JDBCUtil {
    static String url = "jdbc:mysql://localhost:3306/test_db1?characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&useSSL=false";
    static String username = "root";
    static String password = "root";

    //1.加载驱动 如果是mysql8.0以上版本，驱动需要加cj,如果是5版本，不需要加cj
    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e + "驱动加载失败");
        }
    }

   public static Connection getConnection() {
       //2.创建连接
       try {
           return DriverManager.getConnection(url, username, password);
       } catch (SQLException e) {
           throw new RuntimeException(e+"数据库连接失败");
       }
   }

    public static void close(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet) {
        //6.关闭资源
        try {
            if (resultSet != null) {
                resultSet.close();
            }
            if (preparedStatement != null) {
                preparedStatement.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e+"结果集关闭失败");
        }



    }

    public static void close(Connection connection, PreparedStatement preparedStatement) {
        //6.关闭资源
        try {
            if (preparedStatement != null) {
                preparedStatement.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e + "结果集关闭失败");
        }


    }



}